package cn.com.headfree.server.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import com.gta.edu.sdk.base.dao.impl.BaseDaoImpl;
import com.gta.edu.sdk.util.IdGen;

import cn.com.headfree.server.dao.IServerRecordDao;
import cn.com.headfree.server.entity.TZuulServerRecord;

/**
 * @description:路由访问信息实现类
 * @Author: panl
 * @Date: 2020/3/2 15:48
 */
@Repository("serverRecordDao")
public class ServerRecordImpl extends BaseDaoImpl<TZuulServerRecord> implements IServerRecordDao {
    private static final Logger logger = Logger.getLogger(ServerRecordImpl.class);

    private static final int RECORD_COUNT = 1000;

    @Override
    public int saveZuulRecord(List<TZuulServerRecord> zuulServerRecord) {
        String temp = "insert into t_zuul_server_record(id,visit_ip,be_visit_ip,be_visit_port,be_visit_type,be_visit_path,visit_time) values";
        StringBuilder sql = null;
        Map<String, Object> params = new HashMap<String, Object>(zuulServerRecord.size());
        // 循环提交记录次数
        int forNum = zuulServerRecord.size() % RECORD_COUNT > 0 ? zuulServerRecord.size() / RECORD_COUNT + 1
                : zuulServerRecord.size() / RECORD_COUNT;
        // 得到循环次数，每次提交100条记录
        int start = 0;
        int end = 0;
        int resultNum = 0;
        logger.info("开始访问路由记录数据sql整合");
        for (int i = 0; i < forNum; i++) {
            sql = new StringBuilder(temp);
            start = i * RECORD_COUNT;
            end = (i + 1) * RECORD_COUNT - 1;
            if (i == forNum - 1) {
                end = zuulServerRecord.size() - 1;
            }
            for (int j = start; j <= end; j++) {
                sql.append("(#{id").append(j).append("},#{visit_ip").append(j).append("},#{be_visit_ip").append(j)
                        .append("},#{be_visit_port").append(j).append("},#{be_visit_type").append(j)
                        .append("},#{be_visit_path").append(j).append("},#{visit_time").append(j).append("})");
                if (j != end) {
                    sql.append(",");
                }
                params.put("id" + j, IdGen.uuid());
                params.put("visit_ip" + j, zuulServerRecord.get(j).getVisit_ip());
                params.put("be_visit_ip" + j, zuulServerRecord.get(j).getBe_visit_ip());
                params.put("be_visit_port" + j, zuulServerRecord.get(j).getBe_visit_port());
                params.put("be_visit_type" + j, zuulServerRecord.get(j).getBe_visit_type());
                params.put("be_visit_path" + j, zuulServerRecord.get(j).getBe_visit_path());
                params.put("visit_time" + j, zuulServerRecord.get(j).getVisit_time());
            }
            logger.info("开始访问路由记录数据批量入表");
            resultNum = this.executeSql(sql.toString(), params);
            logger.info("开始访问路由记录数据批量入表完成");
        }
        return resultNum;
    }
}
